package com.aaa.sbm.controller;

import com.aaa.sbm.entity.Dept;
import com.aaa.sbm.service.DeptService;
import com.aaa.sbm.util.Result;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.ArrayList;
import java.util.List;

import static org.mockito.ArgumentMatchers.anyInt;

@RunWith(MockitoJUnitRunner.class)
public class DeptControllerTest {

    @InjectMocks
    private DeptController deptController;

    @Mock
    private DeptService deptService;

    // Setup common objects or configurations before each test
    @Before
    public void setUp() {
        List<Dept> mockDeptList = new ArrayList<>();
        Dept mockDept = new Dept();
        mockDept.setDeptNo(1);
        mockDept.setDeptName("部门名称");
        //mockDept.setPhone("12345678");
        // mockDept.setUrl("www.example.com");
        mockDeptList.add(mockDept);

        // Stubbing service layer
        Mockito.when(deptService.queryById(anyInt())).thenReturn(mockDept);
    }

    @Test
    public void testQueryByIdBSuccess() {
        Result result = deptController.queryByIdB(1);
        Assert.assertNotNull("Result should not be null", result);
        Assert.assertTrue("Result data should not be empty", ((List<?>) result.getData()).size() > 0);
        Dept dept = (Dept) ((List<?>) result.getData()).get(0);
        Assert.assertEquals("DeptNo should match", Integer.valueOf(1), dept.getDeptNo());
        Assert.assertEquals("DeptName should match", "部门名称", dept.getDeptName());
    }

    @Test
    public void testQueryByIdBWithInvalidDeptNo() {
        Result result = deptController.queryByIdB(999);
        // Assuming your service returns null or an empty list when no department is found
        Assert.assertNotNull("Result should not be null even if no department is found", result);
        Assert.assertTrue("Result data should be empty when no department is found", ((List<?>) result.getData()).isEmpty());
    }

    @Test
    public void testQueryByIdBWithException() {
        // Stubbing service layer to throw an exception
        Mockito.when(deptService.queryById(anyInt())).thenThrow(new RuntimeException("Database connection failed"));

        // Here we test how the controller handles exceptions from the service layer
        // This assumes your controller or a higher layer handles exceptions and returns a meaningful result
        // Adjust according to your actual exception handling mechanism
        try {
            deptController.queryByIdB(1);
            Assert.fail("Expected an exception to be thrown");
        } catch (RuntimeException e) {
            Assert.assertEquals("Exception message should match", "Database connection failed", e.getMessage());
        }
    }
}